package org.foj.action;

import org.appfuse.webapp.action.BaseAction;
import org.foj.model.Comment;
import org.foj.model.Issue;
import org.foj.service.CommentManager;
import org.foj.service.IssueManager;

import java.util.List;

/**
 * @author jeremy anderson
 */
public class IssueAction extends BaseAction {

    private IssueManager issueManager;
    private CommentManager commentManager;
    private List<Issue> issues;
    private List<Comment> comments;
    private Issue issue;
    private Long id;

    public void setIssueManager(IssueManager issueManager) {
        this.issueManager = issueManager;
    }

    public void setCommentManager(CommentManager commentManager) {
        this.commentManager = commentManager;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Issue getIssue() {
        return issue;
    }

    public void setIssue(Issue issue) {
        this.issue = issue;
    }

    public List<Issue> getIssues() {
        return issues;
    }

    public List<Comment> getComments() {
        return comments;
    }

    public void setComments(List<Comment> comments) {
        this.comments = comments;
    }

    public String list() {
        issues = issueManager.getAll();
        return SUCCESS;
    }

    public String delete() {
        issueManager.remove(issue.getId());
        saveMessage(getText("issue.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            issue = issueManager.get(id);
        } else {
            issue = new Issue();
        }

        comments = commentManager.findCommentsByIssueId(issue.getId());

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return CANCEL;
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (issue.getId() == null);

        issue = issueManager.save(issue);

        String key = isNew ? "issue.added" : "issue.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }

    }

}
